package com.tool.weixin.api;

import net.sf.json.JSONObject;

import org.slf4j.Logger;

import com.tool.weixin.WeixinConfig;
import com.tool.weixin.cache.WeixinCacheManager;
import com.tool.weixin.model.AccessToken;
import com.tool.weixin.util.HttpUtils;

public class AccessTokenApi {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(AccessTokenApi.class);

     /**
     * 获取access_token的接口地址（GET） 限2000（次/天）
     */
    private final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 获取access_token
     *
     * @return
     */
    public static AccessToken getAccessToken() {
        return getAccessToken(WeixinConfig.getInstance().getAppid(), WeixinConfig.getInstance().getAppsecret());
    }

    /**
     * 获取access_token
     *
     * @param appid     凭证
     * @param appsecret 密钥
     * @return
     */
    public static AccessToken getAccessToken(String appid, String appsecret) {
        AccessToken accessToken = WeixinCacheManager.getInstance().getAccessToken();
        if (accessToken != null) return accessToken;

        String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        JSONObject jsonObject = HttpUtils.httpRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
                WeixinCacheManager.getInstance().saveAccessToken(accessToken);
            } catch (Exception e) {
                accessToken = null;
                // 获取token失败
                logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }
}
